package controllers

import (
	"encoding/json"
	"fmt"
	"strconv"
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/server/web"
)

// CouponIssueController 优惠券发放控制器
type CouponIssueController struct {
	web.Controller
}

// CouponIssueListRequest 优惠券发放列表请求参数
type CouponIssueListRequest struct {
	Page     int    `json:"page" form:"page"`
	PageSize int    `json:"pageSize" form:"pageSize"`
	CouponId int64  `json:"coupon_id" form:"coupon_id"`
	MemberId int64  `json:"member_id" form:"member_id"`
	Status   int8   `json:"status" form:"status"`
	Code     string `json:"code" form:"code"`
}

// CouponIssueCreateRequest 创建优惠券发放请求参数
type CouponIssueCreateRequest struct {
	CouponId   int64  `json:"coupon_id"`
	MemberId   int64  `json:"member_id"`
	Code       string `json:"code"`
	ExpireTime int64  `json:"expire_time"`
}

// CouponIssueBatchRequest 批量发放优惠券请求参数
type CouponIssueBatchRequest struct {
	CouponId   int64   `json:"coupon_id"`
	MemberIds  []int64 `json:"member_ids"`
	ExpireTime int64   `json:"expire_time"`
}

// List 获取优惠券发放列表
func (c *CouponIssueController) List() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析分页参数
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 10)

	// 解析过滤条件
	filters := make(map[string]interface{})

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	// 会员ID
	if memberId, err := c.GetInt64("member_id", 0); err == nil && memberId > 0 {
		filters["member_id"] = memberId
	}

	// 优惠券ID
	if couponId, err := c.GetInt64("coupon_id", 0); err == nil && couponId > 0 {
		// 验证优惠券权限
		if permResult.Admin.FranchiseId > 0 {
			coupon, err := models.GetCouponById(couponId)
			if err != nil || coupon == nil || coupon.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = map[string]interface{}{
					"success": false,
					"message": "无权查看该优惠券的发放记录",
				}
				c.ServeJSON()
				return
			}
		}
		filters["coupon_id"] = couponId
	}

	// 活动ID
	if activityId, err := c.GetInt64("activity_id", 0); err == nil && activityId > 0 {
		// 验证活动权限
		if permResult.Admin.FranchiseId > 0 {
			activity, err := models.GetCouponActivityById(activityId)
			if err != nil || activity == nil || activity.FranchiseId != permResult.Admin.FranchiseId {
				c.Data["json"] = map[string]interface{}{
					"success": false,
					"message": "无权查看该活动的发放记录",
				}
				c.ServeJSON()
				return
			}
		}
		filters["activity_id"] = activityId
	}

	// 使用状态
	if status, err := c.GetInt8("status", -1); err == nil && status != -1 {
		filters["status"] = status
	}

	// 时间范围
	if startTime, err := c.GetInt64("start_time", 0); err == nil && startTime > 0 {
		filters["start_time"] = startTime
	}

	if endTime, err := c.GetInt64("end_time", 0); err == nil && endTime > 0 {
		filters["end_time"] = endTime
	}

	// 获取优惠券发放记录列表
	issues, total, err := models.GetCouponIssueList(page, pageSize, filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券发放记录列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回优惠券发放记录列表
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券发放记录列表成功",
		"data": map[string]interface{}{
			"list":  issues,
			"total": total,
			"page":  page,
			"size":  pageSize,
		},
	}
	c.ServeJSON()
}

// GetOne 获取优惠券发放详情
func (c *CouponIssueController) GetOne() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取ID参数
	idStr := c.Ctx.Input.Param(":id")
	id, err := strconv.ParseInt(idStr, 10, 64)
	if err != nil || id <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠券发放ID",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券发放记录
	issue, err := models.GetCouponIssueById(id)
	if err != nil || issue == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券发放记录不存在",
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能查看自己加盟商的数据
	if permResult.Admin.FranchiseId > 0 && issue.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权查看该优惠券发放记录",
		}
		c.ServeJSON()
		return
	}

	// 获取关联的优惠券信息
	coupon, _ := models.GetCouponById(issue.CouponId)

	// 获取关联的会员信息
	member, _ := models.GetMemberById(issue.MemberId, permResult.Admin.FranchiseId)

	// 构建响应数据
	data := map[string]interface{}{
		"issue": issue,
	}
	if coupon != nil {
		data["coupon"] = coupon
	}
	if member != nil {
		data["member"] = member
	}

	// 返回优惠券发放记录详情
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "获取优惠券发放记录详情成功",
		"data":    data,
	}
	c.ServeJSON()
}

// Create 创建优惠券发放
func (c *CouponIssueController) Create() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req CouponIssueCreateRequest
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求参数",
		}
		c.ServeJSON()
		return
	}

	// 检查优惠券是否存在及权限验证
	coupon, err := models.GetCouponById(req.CouponId)
	if err != nil || coupon == nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "优惠券不存在",
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能操作自己加盟商的优惠券
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作该优惠券",
		}
		c.ServeJSON()
		return
	}

	// 创建优惠券发放
	issue := &models.CouponIssue{
		CouponId:   req.CouponId,
		MemberId:   req.MemberId,
		Code:       req.Code,
		Status:     0, // 未使用
		ExpireTime: req.ExpireTime,
	}

	// 设置创建者信息
	issue.CreatedBy = permResult.Admin.Username
	issue.UpdatedBy = permResult.Admin.Username
	issue.BeforeInsert()

	// 保存到数据库
	id, err := models.CreateCouponIssue(issue)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建优惠券发放失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "创建优惠券发放成功",
		"data": map[string]interface{}{
			"id": id,
		},
	}
	c.ServeJSON()
}

// BatchIssue 批量发放优惠券
func (c *CouponIssueController) BatchIssue() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		CouponId  int64   `json:"coupon_id"`
		MemberIds []int64 `json:"member_ids"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数解析失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	if req.CouponId <= 0 || len(req.MemberIds) == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的参数",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券信息
	coupon, err := models.GetCouponById(req.CouponId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能操作自己加盟商的优惠券
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作该优惠券",
		}
		c.ServeJSON()
		return
	}

	// 遍历会员ID列表，为每个会员发放优惠券
	var successCount, failCount int
	for _, memberId := range req.MemberIds {
		// 检查会员是否存在
		member, err := models.GetMemberById(memberId, permResult.Admin.FranchiseId)
		if err != nil {
			failCount++
			continue
		}

		// 检查该会员已领取的该优惠券数量
		if coupon.PerLimit > 0 {
			count, _ := models.GetMemberCouponIssueCount(memberId, req.CouponId)
			if int(count) >= coupon.PerLimit {
				failCount++
				continue
			}
		}

		// 创建优惠券发放记录
		now := time.Now().Unix()
		validFrom := now
		validUntil := now + int64(coupon.ValidDays*24*60*60)

		// 生成唯一的优惠券码
		couponCode := utils.GenerateCouponCode("CP", 12)

		issue := &models.CouponIssue{
			MemberId:   member.Id,
			CouponId:   req.CouponId,
			ActivityId: 0, // 手动发放，无活动ID
			Code:       couponCode,
			Status:     0, // 未使用
			ValidFrom:  validFrom,
			ValidUntil: validUntil,
		}

		// 设置基本模型字段
		issue.BaseModel.CreatedAt = now
		issue.CreatedBy = permResult.Admin.Username

		id, err := models.CreateCouponIssue(issue)
		if err != nil || id <= 0 {
			failCount++
		} else {
			successCount++
			// 更新优惠券已发放数量
			models.IncreaseCouponIssuedCount(req.CouponId)
		}
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": fmt.Sprintf("批量发放优惠券完成，成功：%d，失败：%d", successCount, failCount),
		"data": map[string]interface{}{
			"success_count": successCount,
			"fail_count":    failCount,
		},
	}
	c.ServeJSON()
}

// Cancel 取消优惠券发放
func (c *CouponIssueController) Cancel() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取发放记录ID
	issueID, err := c.GetInt64("id")
	if err != nil || issueID <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的发放记录ID",
		}
		c.ServeJSON()
		return
	}

	// 获取发放记录信息
	issue, err := models.GetCouponIssueById(issueID)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取发放记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 检查优惠券所属权限
	coupon, err := models.GetCouponById(issue.CouponId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能操作自己加盟商的优惠券发放记录
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作该优惠券发放记录",
		}
		c.ServeJSON()
		return
	}

	// 检查优惠券状态
	if issue.Status != 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "只能取消未使用的优惠券",
		}
		c.ServeJSON()
		return
	}

	// 更新优惠券状态为已取消
	issue.Status = 2 // 已取消
	issue.UpdatedBy = permResult.Admin.Username
	issue.UpdatedAt = time.Now().Unix()

	if err := models.UpdateCouponIssue(issue); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "取消优惠券失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回取消结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "优惠券已成功取消",
		"data":    issue,
	}
	c.ServeJSON()
}

// FilterIssue 根据条件筛选发放优惠券
func (c *CouponIssueController) FilterIssue() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var req struct {
		CouponId     int64   `json:"coupon_id"`
		Level        int     `json:"level"`
		RegStartTime int64   `json:"reg_start_time"`
		RegEndTime   int64   `json:"reg_end_time"`
		MinConsume   float64 `json:"min_consume"`
		MaxConsume   float64 `json:"max_consume"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &req); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数解析失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	if req.CouponId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的优惠券ID",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券信息，并验证权限
	coupon, err := models.GetCouponById(req.CouponId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券信息失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能操作自己加盟商的优惠券
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作该优惠券",
		}
		c.ServeJSON()
		return
	}

	// 构建筛选条件
	filters := make(map[string]interface{})

	// 加盟商管理员只能筛选自己加盟商的会员
	if permResult.Admin.FranchiseId > 0 {
		filters["franchise_id"] = permResult.Admin.FranchiseId
	}

	if req.Level > 0 {
		filters["level"] = req.Level
	}

	if req.RegStartTime > 0 {
		filters["reg_start_time"] = req.RegStartTime
	}

	if req.RegEndTime > 0 {
		filters["reg_end_time"] = req.RegEndTime
	}

	if req.MinConsume >= 0 {
		filters["min_consume"] = req.MinConsume
	}

	if req.MaxConsume > 0 {
		filters["max_consume"] = req.MaxConsume
	}

	// 获取符合条件的会员列表
	members, err := models.GetMembersByFilters(filters)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取符合条件的会员列表失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	if len(members) == 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "没有符合条件的会员",
		}
		c.ServeJSON()
		return
	}

	// 批量发放优惠券
	successCount := 0
	failCount := 0
	failMembers := make([]int64, 0)

	for _, member := range members {
		// 创建优惠券发放记录
		issue := models.CouponIssue{
			MemberId:   member.Id,
			CouponId:   req.CouponId,
			ActivityId: 0, // 手动发放，无活动ID
			Status:     0, // 未使用
			ValidFrom:  time.Now().Unix(),
			ValidUntil: time.Now().AddDate(0, 0, int(coupon.PerLimit)).Unix(), // 使用优惠券的有效期设置
		}
		issue.BeforeInsert()
		issue.CreatedBy = permResult.Admin.Username
		issue.UpdatedBy = permResult.Admin.Username

		id, err := models.CreateCouponIssue(&issue)
		if err != nil || id <= 0 {
			failCount++
			failMembers = append(failMembers, member.Id)
			continue
		}

		successCount++
	}

	// 返回发放结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "条件筛选批量发放优惠券完成",
		"data": map[string]interface{}{
			"total_members": len(members),
			"success_count": successCount,
			"fail_count":    failCount,
			"fail_members":  failMembers,
		},
	}
	c.ServeJSON()
}

// Issue 发放优惠券
func (c *CouponIssueController) Issue() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析请求参数
	var requestData struct {
		CouponId   int64 `json:"coupon_id"`
		MemberId   int64 `json:"member_id"`
		ActivityId int64 `json:"activity_id"`
	}

	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &requestData); err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无效的请求数据",
		}
		c.ServeJSON()
		return
	}

	// 参数验证
	if requestData.CouponId <= 0 || requestData.MemberId <= 0 {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "参数不完整",
		}
		c.ServeJSON()
		return
	}

	// 获取优惠券信息
	coupon, err := models.GetCouponById(requestData.CouponId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取优惠券信息失败",
		}
		c.ServeJSON()
		return
	}

	// 加盟商管理员只能操作自己加盟商的优惠券
	if permResult.Admin.FranchiseId > 0 && coupon.FranchiseId != permResult.Admin.FranchiseId {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "无权操作该优惠券",
		}
		c.ServeJSON()
		return
	}

	// 检查会员是否属于当前加盟商
	if permResult.Admin.FranchiseId > 0 {
		member, err := models.GetMemberById(requestData.MemberId, permResult.Admin.FranchiseId)
		if err != nil || member == nil || member.FranchiseId != permResult.Admin.FranchiseId {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "无权为该会员发放优惠券",
			}
			c.ServeJSON()
			return
		}
	}

	// 检查优惠券是否可发放
	available, message := models.CheckCouponAvailable(requestData.CouponId, requestData.MemberId)
	if !available {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": message,
		}
		c.ServeJSON()
		return
	}

	// 创建优惠券发放记录
	now := time.Now().Unix()
	validFrom := now
	validUntil := now + int64(coupon.ValidDays*24*60*60)

	// 生成唯一的优惠券码
	couponCode := utils.GenerateCouponCode("CP", 12)

	issue := &models.CouponIssue{
		MemberId:   requestData.MemberId,
		CouponId:   requestData.CouponId,
		ActivityId: requestData.ActivityId,
		Code:       couponCode,
		Status:     0, // 未使用
		ValidFrom:  validFrom,
		ValidUntil: validUntil,
	}

	// 设置基本模型字段
	issue.BaseModel.CreatedAt = now
	issue.CreatedBy = permResult.Admin.Username

	// 保存发放记录
	id, err := models.CreateCouponIssue(issue)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "创建优惠券发放记录失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 更新优惠券已发放数量
	models.IncreaseCouponIssuedCount(requestData.CouponId)

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"message": "优惠券发放成功",
		"data": map[string]interface{}{
			"id":   id,
			"code": couponCode,
		},
	}
	c.ServeJSON()
}
